package com.hsyt.pfc.core.queue;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description: 等待消息队列抽象实现类
 * @ClassName: AbstractWaitingQueueListener
 * @Package: com.hsyt.pfc.core.queue
 * @Author: wangze@hsyuntai.com
 * @Date: 2018年9月30日 9:17
 * @Copyright: 版权归 HSYUNTAI 所有
 */
public abstract class AbstractWaitingQueueListener implements WaitingQueueListener {

    private static final Logger log = LoggerFactory.getLogger(AbstractWaitingQueueListener.class);

    @Override
    public final void onCreate(final WaitingQueueTask task) {
        try {
            log.debug("执行等待队列任务");
            methodReflect(task.getTarget(), task.getMethod(), task.getParamters());
            Thread.sleep(12000);
            onFinsh(task);
        } catch (Exception e) {
            onError(task, e);
        }
    }

    private final void methodReflect(Object obj, String methodName, List<Object> args) throws Exception {
        try {
            Class[] argsClass = null;
            // 1.获取参数类型数组
            if (CollectionUtils.isNotEmpty(args)) {
                argsClass = args.stream().map(param -> param.getClass()).toArray(array -> new Class[args.size()]);
            }
            //2.反射获得方法
            Method methodReflect = obj.getClass().getMethod(methodName, argsClass);
            //3.调用此方法
            methodReflect.invoke(obj, args.toArray());
        } catch (Exception e) {
            log.error("等待队列监听器反射执行方法失败,target：{} , method: {}, args: {} ,error: {}", obj, methodName, args, e);
            throw e;
        }
    }

}
